from flask import Flask, render_template, request, redirect, url_for, flash, session
import pymysql

app = Flask(__name__)
app.secret_key = 'zzp'


# 数据库连接配置
def get_db_connection():
    return pymysql.connect(
        host='localhost',
        user='root',
        password='',
        db='rainfallvisualization',
        charset='utf8mb4',
        cursorclass=pymysql.cursors.DictCursor
    )


# 退出账号
@app.route('/logout')
def logout():
    # 清除用户会话数据
    session.clear()
    flash('您已成功退出登录。', 'success')
    return redirect(url_for('login'))  # 返回登录页面


# 注册页面
@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        username = request.form['username']
        email = request.form['email']
        password = request.form['password']
        confirm_password = request.form['confirmPassword']

        # 确认密码匹配
        if password != confirm_password:
            flash('密码不匹配！', 'danger')
            return redirect(url_for('register'))

        # 插入用户数据到数据库
        connection = get_db_connection()
        try:
            with connection.cursor() as cursor:
                sql = "INSERT INTO users (email, password, username, role) VALUES (%s, %s, %s, 'user')"
                cursor.execute(sql, (email, password, username))
                connection.commit()
                flash('注册成功，请登录。', 'success')
                return redirect(url_for('login'))
        except pymysql.IntegrityError:
            flash('该电子邮件已被注册，请使用其他电子邮件。', 'danger')
            return redirect(url_for('register'))
        except Exception as e:
            flash(f'发生错误：{str(e)}', 'danger')
            return redirect(url_for('register'))
        finally:
            connection.close()

    return render_template('register.html')


# 登录路由
@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        email = request.form['email']
        password = request.form['password']

        # 查询用户信息
        connection = get_db_connection()
        try:
            with connection.cursor() as cursor:
                sql = "SELECT * FROM users WHERE email = %s"
                cursor.execute(sql, (email,))
                user = cursor.fetchone()

                # 校验用户身份
                if user and user['password'] == password:
                    # 登录成功，设置会话
                    session['logged_in'] = True
                    session['username'] = user['username']
                    session['role'] = user['role']

                    # 更新 last_login 时间
                    update_last_login(user['id'], connection)

                    # 根据用户角色跳转到不同页面
                    if user['role'] == 'admin':
                        return redirect(url_for('admin_dashboard'))
                    elif user['role'] == 'user':
                        return redirect(url_for('user_dashboard'))
                    else:
                        flash('您已被平台拉黑')
                else:
                    flash('邮箱或密码错误，请重试。', 'danger')
        finally:
            connection.close()

    return render_template('login.html')


# 更新用户的上次登录时间
def update_last_login(user_id, connection):
    with connection.cursor() as cursor:
        sql = "UPDATE users SET last_login = NOW() WHERE id = %s"
        cursor.execute(sql, (user_id,))
        connection.commit()


# 管理员首页
@app.route('/admin/home')
def admin_dashboard():
    if 'logged_in' in session and session['role'] == 'admin':
        return render_template('admin.html')
    else:
        return redirect(url_for('login'))


# 管理员_用户管理页面，处理显示、搜索、添加、删除和编辑功能
@app.route('/admin/user-management', methods=['GET', 'POST'])
def user_management():
    connection = get_db_connection()
    per_page = 10  # 每页显示的用户数量
    page = int(request.args.get('page', 1))  # 获取当前页码，默认为1

    if request.method == 'POST':
        action = request.form.get('action')
        print(f"接收到的操作类型: {action}")  # 调试输出

        # 添加用户
        if action == 'add_user':
            username = request.form['username']
            email = request.form['email']
            password = request.form['password']
            role = request.form['role']

            try:
                with connection.cursor() as cursor:
                    sql = "INSERT INTO users (username, email, password, role) VALUES (%s, %s, %s, %s)"
                    cursor.execute(sql, (username, email, password, role))
                    connection.commit()
                    flash('用户添加成功。', 'success')
            except pymysql.IntegrityError:
                flash('用户添加失败：该邮箱已被注册。', 'danger')
            finally:
                return redirect(url_for('user_management'))

        # 批量删除用户
        elif action == 'bulk_delete':
            user_ids = request.form.getlist('user_ids')
            if user_ids:
                try:
                    with connection.cursor() as cursor:
                        sql = "DELETE FROM users WHERE id IN %s"
                        cursor.execute(sql, (tuple(user_ids),))
                        connection.commit()
                        flash('用户删除成功。', 'success')
                except Exception as e:
                    flash(f'删除失败：{str(e)}', 'danger')
            return redirect(url_for('user_management'))  # 删除后立即返回，避免执行其他逻辑

        # 编辑用户
        elif action == 'edit_user':
            user_id = request.form['user_id']
            new_role = request.form['role']
            try:
                with connection.cursor() as cursor:
                    sql = "UPDATE users SET role = %s WHERE id = %s"
                    cursor.execute(sql, (new_role, user_id))
                    connection.commit()
                    flash('用户角色更新成功。', 'success')
            except Exception as e:
                flash(f'更新失败：{str(e)}', 'danger')
            finally:
                return redirect(url_for('user_management'))

    # 获取用户列表并应用分页
    with connection.cursor() as cursor:
        offset = (page - 1) * per_page
        sql = "SELECT * FROM users LIMIT %s OFFSET %s"
        cursor.execute(sql, (per_page, offset))
        users = cursor.fetchall()

        # 获取总用户数来计算总页数
        cursor.execute("SELECT COUNT(*) FROM users")
        total_users = cursor.fetchone()['COUNT(*)']
        total_pages = (total_users + per_page - 1) // per_page  # 向上取整计算总页数

    # 返回模板，并传递 per_page 变量
    return render_template('admin-user-management.html', users=users, page=page, total_pages=total_pages,
                           per_page=per_page)


# 用户首页
@app.route('/user/home')
def user_dashboard():
    if 'logged_in' in session and session['role'] == 'user':
        return render_template('home.html')
    else:
        return redirect(url_for('login'))


@app.route('/')
def index():
    return render_template('login.html')


if __name__ == '__main__':
    app.run(debug=True)
